<template>
	<el-table
		ref="gridDom"
		size="small"
		style="width: 100%"
		:data="tableData"
		:height="height"
		:stripe="stripe"
		:border="border"
		:fit="fit"
		:highlight-current-row="highlightCurrentRow"
		:current-row-key="rowKey"
		:row-key="rowKey"
		@selection-change="selectionChange"
		@current-change="currentChange"
		@cell-click="cellClick"
	>
		<!--显示选择框-->
		<!-- <el-table-column type="selection" width="55"> </el-table-column> -->
		<!--显示字段列表-->
		<el-table-column
			v-for="(item, index) in filterColumns"
			:key="'grid_list_' + index"
			:fixed="item.fixed"
			v-bind="item"
			:label="item.title"
			:prop="item.field"
			:min-width="50"
			:formatter="myformatter"
		>
			<template v-if="item.slots" v-slot="scope">
				<slot
					v-if="typeof item.slots.default === 'object' && item.slots.default && (!item.slots.edit || scope.row[rowKey] !== selectColumnKey)"
					name="default"
					:row="scope"
				>
					{{ scope.row[item.field] }}
				</slot>
				<slot
					v-if="typeof item.slots.default === 'string' && item.slots.default && (!item.slots.edit || scope.row[rowKey] !== selectColumnKey)"
					:name="item.slots.default"
					:row="scope.row"
				>
				</slot>
				<slot v-if="typeof item.slots.edit === 'object' && item.slots.edit && scope.row[rowKey] === selectColumnKey" name="edit" :row="scope">
					<component :is="item.slots.edit.slotType" v-bind="item.slots.edit.attrs" v-on="item.slots.edit.events"> </component>
				</slot>
				<slot
					v-if="typeof item.slots.edit === 'string' && item.slots.edit && scope.row[rowKey] === selectColumnKey"
					:name="item.slots.edit"
					:row="scope.row"
				>
				</slot>
			</template>
			<!-- <template v-for="(item, key, index) in slotList" :key="index" v-slot:[key]>
				<slot :name="key"> {{ key }} </slot>
			</template> -->
		</el-table-column>
		<!--右面的操作列-->
	</el-table>
</template>

<script lang="ts">
import { computed, defineComponent, inject, onMounted, reactive, ref, toRefs } from 'vue';
// 表单控件的属性
import { gridProps } from '../lib/mapController';

/**
 * 列表的单选和多选的事件
 */
const choiceManage = (props, emit, gridDom) => {
	// 是否单选触发
	let isCurrenting = false;
	// 是否多选触发
	let isMoring = false;

	// 单选
	const currentChange = (row) => {
		if (isMoring) return; // 多选代码触发
		if (row === null) return; // 清空

		isCurrenting = true;
		gridDom.value.clearSelection(); // 清空多选
		gridDom.value.toggleRowSelection(row); // 设置复选框
		gridDom.value.setCurrentRow(row); // 设置单选
		// 记录
		props.selection.dataId = row[props.idName];
		props.selection.dataIds[0] = row[props.idName];
		props.selection.row = row;
		props.selection.rows = row;

		isCurrenting = false;

		emit('current-change', props.selection.row);
	};

	// 多选
	const selectionChange = (rows) => {
		if (isCurrenting) return;
		// 记录
		if (typeof props.selection.dataIds === 'undefined') {
			props.selection.dataIds = [];
		}
		props.selection.dataIds.length = 0; // 清空
		// 设置多选
		rows.forEach((item) => {
			if (typeof item !== 'undefined' && item !== null) {
				props.selection.dataIds.push(item[props.idName]);
			}
		});
		props.selection.rows = rows;
		// 设置单选
		switch (rows.length) {
			case 0:
				// 清掉单选
				gridDom.value.setCurrentRow();
				props.selection.dataId = '';
				props.selection.row = {};
				break;
			case 1:
				isMoring = true;
				// 设置新单选
				gridDom.value.setCurrentRow(rows[0]);
				isMoring = false;
				props.selection.row = rows[0];
				props.selection.dataId = rows[0][props.idName];
				break;
			default:
				// 清掉单选
				gridDom.value.setCurrentRow();
				props.selection.row = rows[rows.length - 1];
				props.selection.dataId = props.selection.row[props.idName];
		}
	};

	return {
		currentChange, // 单选
		selectionChange, // 多选
	};
};

/**
 * * height: 250, // 高度
 * * colOrder: [101], // 显示顺序
 * * fixedIndex: 0 // 锁定的列数
 * * itemMeta: {
 * * --101: {
 * * ----id: 101,
 * * ----label: '编号11',
 * * ----prop: 'code',
 * * ----width: 120
 * * --}
 */
export default defineComponent({
	name: 'zh-el-table',
	inheritAttrs: false,
	props: {
		...gridProps,
		//默认 default paging 分页
		type: {
			type: String,
			default: 'paging',
		},
		data: {
			type: Array,
			default: () => [],
		},
		fit: {
			type: Boolean,
			default: () => true,
		},
		//请求数据的url
		url: {
			type: String,
			default: '',
		},
	},
	setup(props, context) {
		// console.log('\ngrid---props', props) //
		// 获取 table 的 dom 和其他，
		const gridDom = ref(null);
		onMounted(() => {
			state.slotList = context.slots;
		});

		// 列表选项的事件
		const {
			currentChange, // 单选
			selectionChange, // 多选
		} = choiceManage(props, context.emit, gridDom);

		// 格式化
		const myformatter = (row, column, cellValue) => {
			// console.log('\nrow:', row, 'col:', column) //
			// console.log('cellValue:', cellValue, 'index:', index) //
			if (Array.isArray(cellValue)) {
				return cellValue.join(',');
			}
			if (typeof cellValue === 'boolean') {
				return cellValue.toString();
			}
			return row[column.property]; // realWidth
		};

		const state = reactive({
			tablePage: {
				total: 0,
				pageNum: 1,
				currentPage: 1,
				pageSize: 20,
			},
			queryParam: {} as any,
			timeout: 30000,
			isAllChecked: false,
			loading: false,
			tableData: props.data,
			slotList: [] as any,
			currentUrl: props.url,
			selectColumnKey: '',
		});
		const http: any = inject('$http');

		const filterColumns = computed(() => {
			return props.columns.filter((item) => (typeof item.visible === 'undefined' ? true : item.visible));
		});

		function query(queryParam: any, url: string, timeout: number) {
			state.tablePage.pageNum = 1;
			state.tablePage.currentPage = 1;
			if (url) {
				state.currentUrl = url;
			}
			if (queryParam) {
				state.queryParam = queryParam;
			}
			if (timeout) {
				state.timeout = timeout;
			}
			state.isAllChecked = false;
			// if (state.showPageLeft) {
			// 	checkboxChangeEvent();
			// 	// zhGrid.value.clearCheckboxReserve();
			// }
			// zhGrid.value.clearCurrentRow();
			// zhGrid.value.clearSelected();
			// zhGrid.value.clearRadioRow();
			// zhGrid.value.clearRadioReserve();
			findTableList();
			// setTimeout(() => {
			// 	that.refs.zhGrid.scrollTo(0, 0);
			// }, 100);
		}
		function findTableList() {
			return new Promise((resolve) => {
				state.loading = true;
				let params = state.queryParam;
				if (props.type === 'paging') {
					params = Object.assign(params, state.tablePage);
				}
				http
					.post(state.currentUrl, params, state.timeout)
					.then((res: any) => {
						let data = [];
						if (props.type === 'paging') {
							data = res.result.list;
						} else {
							if (res.result.list) {
								data = res.result.list;
							} else {
								data = res.result;
							}
						}

						state.tableData = data;
						state.tablePage.total = res.result.total;
						state.tablePage.pageNum = res.result.pageNum;
						state.tablePage.currentPage = res.result.pageNum;
						state.tablePage.pageSize = res.result.pageSize;
						state.loading = false;
						if (data && data.length > 0) {
							resolve(state);
						} else {
							if (res.result.pageNum > 1) {
								params.pageNum = res.result.pages;
								state.loading = true;
								http
									.post(props.url, params)
									.then((res: any) => {
										state.tableData = res.result.list;
										state.tablePage.total = res.result.total;
										state.tablePage.pageNum = res.result.pageNum;
										state.tablePage.currentPage = res.result.pageNum;
										state.tablePage.pageSize = res.result.pageSize;
										state.loading = false;
										resolve(state);
									})
									.catch(() => {
										state.loading = false;
										resolve(state);
									});
							} else {
								resolve(state);
							}
						}
					})
					.catch(() => {
						state.loading = false;
						resolve(state);
					});
			});
		}

		function cellClick(row) {
			// console.log(row, column, c, e);
			state.selectColumnKey = row[props.rowKey];
		}

		return {
			selectionChange, // 多选
			currentChange, // 单选
			gridDom, // table 的 dom
			myformatter, // 格式化
			query,
			...toRefs(state),
			filterColumns,
			cellClick,
		};
	},
});
</script>
